import sys
import os
import fitz  # PyMuPDF
from PyQt5.QtGui import QDesktopServices
from PyQt5.QtWidgets import (QApplication, QMainWindow, QFileDialog,
                             QPushButton, QLabel, QVBoxLayout, QWidget,
                             QProgressBar, QMessageBox, QSpinBox)
from PyQt5.QtCore import Qt, QUrl


class PDFConverter(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('PDF转图片工具')
        self.setFixedSize(300, 300)

        # 主部件
        widget = QWidget()
        layout = QVBoxLayout()

        # 组件初始化
        self.btn_select = QPushButton('选择PDF文件')
        self.btn_convert = QPushButton('开始转换')
        self.btn_open_folder = QPushButton('打开输出文件夹')
        self.label_status = QLabel('状态: 等待选择文件')
        self.progress = QProgressBar()
        self.dpi_spin = QSpinBox()
        self.dpi_spin.setRange(72, 600)
        self.dpi_spin.setValue(300)
        self.dpi_spin.setPrefix("DPI: ")

        # 布局设置
        layout.addWidget(self.btn_select)
        layout.addWidget(QLabel("输出质量(数字越大质量越高,文件越大):"))
        layout.addWidget(self.dpi_spin)
        layout.addWidget(self.btn_convert)
        layout.addWidget(self.btn_open_folder)
        layout.addWidget(self.label_status)
        layout.addWidget(self.progress)
        widget.setLayout(layout)
        self.setCentralWidget(widget)

        # 信号连接
        self.btn_select.clicked.connect(self.select_pdf)
        self.btn_convert.clicked.connect(self.convert_pdf)
        self.btn_open_folder.clicked.connect(self.open_output_folder)
        self.btn_convert.setEnabled(False)
        self.btn_open_folder.setEnabled(False)

    def select_pdf(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择PDF文件", "", "PDF文件 (*.pdf)")
        if file_path:
            self.pdf_path = file_path
            self.label_status.setText(f'已选择: {os.path.basename(file_path)}')
            self.btn_convert.setEnabled(True)

    def convert_pdf(self):
        output_dir = os.path.splitext(self.pdf_path)[0]
        self.output_dir = output_dir
        if not os.path.exists(output_dir):
            os.makedirs(output_dir, exist_ok=True)
        try:
            doc = fitz.open(self.pdf_path)
            total_pages = len(doc)
            self.progress.setRange(0, total_pages)

            for i in range(total_pages):
                page = doc.load_page(i)
                pix = page.get_pixmap(dpi=self.dpi_spin.value())
                pix.save(f"{output_dir}/{os.path.basename(self.pdf_path)}_{i + 1}.png")
                self.progress.setValue(i + 1)
                QApplication.processEvents()

            QMessageBox.information(self, '完成', f'成功转换{total_pages}页')
            self.btn_open_folder.setEnabled(True)

        except Exception as e:
            QMessageBox.critical(self, '错误', f'转换失败: {str(e)}')
        finally:
            self.progress.reset()
            self.label_status.setText("状态: 转换完成")


    def open_output_folder(self):
        if self.output_dir and os.path.exists(self.output_dir):
            QDesktopServices.openUrl(QUrl.fromLocalFile(self.output_dir))
        else:
            QMessageBox.warning(self, '警告', '输出目录不存在或未设置')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = PDFConverter()
    window.show()
    sys.exit(app.exec_())
